package org.yaac.client.widget;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.ToggleButton;

/**
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class ToggleButtonGroup<T> {
	
	public static interface SelectionChangeListener<T> {
		void onSelect(T selectedVal);
	}
	
	private Map<T, ToggleButton> buttonsMap;
	
	private List<SelectionChangeListener<T>> listeners;
	
	public ToggleButtonGroup() {
		this.buttonsMap = new HashMap<T, ToggleButton>();
		this.listeners = new LinkedList<SelectionChangeListener<T>>();
	}
	
	public void addButton(T t, final ToggleButton btn) {
		this.buttonsMap.put(t, btn);
		
		btn.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (btn.isDown()) {
					select(btn);
				} else {
					// ignore the action
					btn.setDown(true);
				}
			}
		});
	}
	
	public void subscribe(SelectionChangeListener<T> listener) {
		this.listeners.add(listener);
	}
	
	public void select(T key) {
		this.select(buttonsMap.get(key));
	}
	
	private void select(ToggleButton btn) {
		// update UI
		for (T key : buttonsMap.keySet()) {
			ToggleButton otherBtn = buttonsMap.get(key);
			
			if (btn == otherBtn) { // notify listeners
				btn.setDown(true);	// may be triggered in code level
				for (SelectionChangeListener<T> listener : listeners) {
					listener.onSelect(key);
				}
			} else {	// reset other button
				otherBtn.setDown(false);
			}
		}
	}
}
